package com.daqsoft.controller.project;

import com.daqsoft.data.project.Attachment;
import com.daqsoft.data.project.Project;
import com.daqsoft.data.project.Task;
import com.daqsoft.dto.GeneralResultEnum;
import com.daqsoft.permission.Verify;
import com.daqsoft.permission.VerifyType;
import com.daqsoft.service.project.AttachmentService;
import com.daqsoft.service.project.ProjectService;
import com.daqsoft.service.project.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 *
 * @author 周麟东 on 10:51
 */
@RestController
@RequestMapping("att")
public class AttachmentController {

    @Autowired
    private AttachmentService attachmentService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ProjectService projectService;
    @Value("${file.dir}")
    private String fileDir;

    @RequestMapping("getAtt")
    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "获取文件列表")
    public GeneralResultEnum getAttByTask(Integer taskId, Integer projectId, Boolean isTask) {
        if (taskId == null && projectId == null) {
            return GeneralResultEnum.FAIL;
        }
        List<Map<String, Object>> list = new ArrayList<>();
        if (isTask && taskId != null) {
            for (Attachment attachment : attachmentService.getAttByTaskId(taskId)) {
                list.add(attachment.toMap());
            }
        }
        if (!isTask && projectId!=null){
            for (Attachment attachment : attachmentService.getAttByProjectId(projectId)) {
                list.add(attachment.toMap());
            }
        }
        return GeneralResultEnum.SUCCESS.setData(list).setDesc("获取文件管理列表成功");
    }

    @RequestMapping("save")
    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "上传文件")
    public GeneralResultEnum save(int taskId, Integer projectId , Boolean isTask ,Attachment attachment, MultipartHttpServletRequest multiReq) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        String uploadFilePath = multiReq.getFile("file").getOriginalFilename();

        String uploadFileSuffix = uploadFilePath.substring(
                uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
        String path = fileDir + File.separator + uuid + "." + uploadFileSuffix;
        InputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = multiReq.getFile("file").getInputStream();
            attachment.setPath(path);
            fos = new FileOutputStream(new File(path));
            byte[] temp = new byte[1024];
            int i = fis.read(temp);
            while (i != -1) {
                fos.write(temp, 0, temp.length);
                fos.flush();
                i = fis.read(temp);
            }
            //保存
            if (isTask){
                Task task = taskService.get(taskId);
                if (task == null){
                    attachmentService.deleteFile(path);
                    return GeneralResultEnum.FAIL.setDesc("任务不存在");
                }
                attachmentService.save(task, attachment);
            }else {
                Project project = projectService.get(projectId);
                if (project == null){
                    attachmentService.deleteFile(path);
                    return GeneralResultEnum.FAIL.setDesc("项目不存在");
                }
                attachmentService.save(project , attachment);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return GeneralResultEnum.FAIL.setDesc("保存文件出错:" + e.getMessage());
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return GeneralResultEnum.SUCCESS;
    }

    @RequestMapping("download")
    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "通过ID下载文件")
    public void downloadFile(int attId, HttpServletResponse response) {
        Attachment attachment = attachmentService.get(attId);
        String uploadFileSuffix = attachment.getPath().substring(
                attachment.getPath().indexOf('.') + 1, attachment.getPath().length());
        String fileName = attachment.getFileName() + "." + uploadFileSuffix;
        BufferedInputStream bis = null;
        try {
            response.addHeader("Content-Disposition",
                    "attachment;filename=\""
                            + new String((fileName)
                            .getBytes("GBK"), "ISO8859_1") + "\"");
            OutputStream os = response.getOutputStream();
            byte[] buff = new byte[1024];
            bis = new BufferedInputStream(new FileInputStream(new File(attachment.getPath())));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping("remove")
    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "删除文件")
    public GeneralResultEnum remove(int attId) {
        Attachment attachment = attachmentService.get(attId);
        if (attachment == null) {
            return GeneralResultEnum.FAIL.setDesc("该数据不存在");
        }
        if (!attachmentService.delete(attachment)) {
            return GeneralResultEnum.FAIL.setDesc("无法删除文件 , 文件已经不存在");
        }
        return GeneralResultEnum.SUCCESS.setDesc("删除成功");
    }

}
